package com.example.kaptcha.demo;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * ClassName: CaptchaController
 * Package: IntelliJ IDEA
 * Description:
 *
 * @Author 谷京京
 * @Create 2023/11/11 16:45
 * @Version 1.0
 */
@RequestMapping("/admin")
@RestController
public class CaptchaController {
    //常量定义: key:全部大写, 单词之间用下划线分割 value:通常是小写, 单词之间用下划线分割.
    private static final String KAPTCHA_SESSION_KEY = "HOME_KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "HOME_KAPTCHA_SESSION_DATE";
    //单位为毫秒
    private static final Long SESSION_TIME_OUT = 60*1000L;
    /**
     * 验证
     * 从session中获取生成的验证码, 比对前端传递的验证码和session中存储的是否一致
     * @param captcha
     * @return
     */
    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session) {
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }
        String saveCaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);
        if(captcha.equals(saveCaptcha)) {
            //比对日期
            if(saveDate == null || System.currentTimeMillis() - saveDate.getTime() < SESSION_TIME_OUT) {
                return true;
            }
        }
        return false;
    }
}
